<template>
  <Page class="min-h-screen bg-gradient-to-br from-[#f5f5f5] to-[#eef2f7] pb-[40rpx]">
    <view class="max-w-[750rpx] mx-auto">
      <!-- 头部区域 -->
      <PageHeader title="能力提升" :showBack="true" :onlyBack="true"/>
      <view
          class="bg-gradient-to-r from-[#165DFF] to-[#1890ff] sticky top-0 z-[2] text-white px-[32rpx] pt-[100rpx] rounded-b-[32rpx] mb-[-40rpx] relative shadow-md">
        <!-- 返回按钮 -->
        <SearchView @search="handleSearch" />
        <view class="flex overflow-x-auto py-[24rpx] gap-x-[20rpx] my-[40rpx_0_24rpx]">
          <view v-for="category in categories" :key="category.id"
                class="flex-0 flex-none bg-white rounded-[24rpx] p-[16rpx] text-center shadow-md min-w-[120rpx] cursor-pointer transition-all duration-300"
                :class="{
            'bg-[#3bd4f6ff] text-[#543bf6ff] font-bold shadow-lg':
              activeCategory === category.id,
            'text-gray-500': activeCategory !== category.id,
          }" @click="activeCategory = category.id">
            <text class="text-[26rpx]">{{ category.name }}</text>
          </view>
        </view>
      </view>

      <!-- 分类区域 -->
      <view class="box-border p-[20rpx] mt-[20rpx]">
        <!-- 精选课程 -->
        <view class="flex justify-between items-center my-[30rpx]">
          <h2 class="text-[32rpx] font-bold text-[#222]">精选课程</h2>
          <view @tap="goMore(1)" class="text-[#165DFF] text-[24rpx]">查看全部
            <IconFont name="right" class="ml-[10rpx]" size="12"/>
          </view>
        </view>
        <view class="grid grid-cols-2 gap-[20rpx] mb-[24rpx]">
          <view v-for="course in currentCuratedCourses" :key="course.id"
                class="bg-white rounded-[24rpx] overflow-hidden shadow-md transition-transform duration-300 hover:translate-y-[-8rpx]"
                @tap="handleCourseClick(course)">
            <view>
              <view class="flex items-center mb-[12rpx] text-[22rpx] text-[#7f8c8d]">
                  <image
                    :src="getImageSrc(course?.cover)"
                    @error="handleImageError"
                    mode="aspectFit"
                    class="w-full h-[200rpx] object-cover bigs"
                  />
              </view>
              <view class="font-bold text-[26rpx] block line-clamp-2 px-[20rpx] mt-2">
                {{ course.title }}
              </view>
              <view class="flex justify-between text-[22rpx] text-[#7f8c8d] p-[20rpx]">
                <view class="flex items-center gap-[6rpx]">
                  <IconFont font-class-name="iconfont" class-prefix="icon" size="16" name="tuandui" />
                  {{
                    course.member_number
                  }}人学习
                </view>
                <view class="text-[#f39c12] font-bold text-[26rpx]">¥{{
                    course.price
                  }}
                </view>
              </view>
            </view>
          </view>
        </view>

        <view v-if="currentCuratedCourses.length === 0" class="text-center text-[24rpx] text-[#7f8c8d]">
          <nut-empty description="暂无数据" />
        </view>

        <!-- 下一页按钮 -->
        <view class="flex justify-center items-center py-[32rpx]">
          <nut-button 
            type="primary" 
            class="rounded-2xl text-[28rpx] px-[64rpx] bg-[#165DFF]" 
            @click="loadMore" 
            :disabled="noMore"
            :loading="loading"
          >
            {{ noMore ? '没有更多了' : '下一页' }}
          </nut-button>
        </view>
      </view>
    </view>
  </Page>
</template>

<script setup lang="ts">
import {computed, onMounted, ref, watch} from "vue";
import Taro, { usePullDownRefresh, useReachBottom } from '@tarojs/taro'
import {IconFont} from "@nutui/icons-vue-taro";
// import {Input as nutInput, Button as nutButton} from "@nutui/nutui-taro";
import SearchView from "@/components/SearchView.vue";
import PageHeader from "@/components/PageHeader.vue";
import {getFullPath, post} from "@/utils/request";
// import { navigator } from '@tarojs/components'
import noneImg from "@/assets/pic/ren.png";
// const noneImg = 'http://www.dzgktf.com/templets/default/images/wtyt.jpg';


//获取课程数据的格式
interface CourseColumn {
  member_id: null,
  teachers_pic: null,
  sign_rate: null,
  teacher_name: null,
  member_number: null,
  number: null, // 添加number字段
  teachers_introduction: null,
  create_time: number,
  pay_number: null,
  title: null,
  type: null,
  cycle_type: null,
  cycle: null,
  cover: null,
  update_time: null | number;
  pay_status: null,
  total_amount: null,
  price: null,
  progress: null,
  id: number,
  introduction: null,
  status: number
}

interface CourseItem {
  columns: CourseColumn;
  columnNames: string[];
  columnValues: (null | number | string)[];
}

//接收精选课程
const allCuratedCourses = ref<any[]>([])
//接收热门推荐
const allpopularRecommendationCourses = ref<any[]>([])
// getCuratedCourses()
// popularRecommendation()
const searchValue = ref("");
function handleSearch(val: string) {
  searchValue.value = val;
  page.value = 1;
  noMore.value = false;
  popularRecommendation(activeCategory.value, false);
}

// 默认图片路径
const defaultImage = noneImg

// 获取图片源，如果为空则使用默认图片
const getImageSrc = (imagePath: string | null) => {
  if (!imagePath || imagePath === 'null' || imagePath === 'undefined' || imagePath.trim() === '') {
    return defaultImage
  }
  return getFullPath(imagePath)
}

// 处理图片加载错误
const handleImageError = (event: any) => {
  event.target.src = defaultImage
  // const target = event.target
  // // 防止死循环：如果当前src已经是默认图片，则不再设置
  // if (target.src !== defaultImage && !target.dataset.fallback) {
  //   target.dataset.fallback = 'true' // 标记已经尝试过fallback
  //   target.src = defaultImage
  // } else {
  //   // 如果默认图片也加载失败，显示一个占位符或隐藏图片
  //   target.style.display = 'none'
  // }
}

//获取精选课程数据
function popularRecommendation(type?: number, isLoadMore: boolean = false) {
  //分页和类型参数
  const queryParams:any = {
    pageNo: isLoadMore ? page.value : 1,  // 加载更多时使用当前页码，否则重置为第1页
    pageSize: 10,        // 每页10条
    title: searchValue.value
  }
  if(type !== undefined){
    queryParams.type = type
  }
  
  post('/training/all', queryParams).then(res => {
    const newData = res.data.map((item: CourseItem) => ({
      teacher_name: item.columns.teacher_name,
      cover: item.columns.cover,
      teachers_pic: item.columns.teachers_pic,
      title: item.columns.title,
      price: item.columns.price,
      member_id: item.columns.member_id,
      member_number: item.columns.number,
      create_time: item.columns.create_time,
      type: item.columns.type,
      id: item.columns.id
    }));
    
    if (isLoadMore) {
      // 加载更多时，追加数据
      allCuratedCourses.value = [...allCuratedCourses.value, ...newData]
    } else {
      // 首次加载或切换分类时，替换数据
      allCuratedCourses.value = newData
    }
    
    // 判断是否还有更多数据
    noMore.value = newData.length < 10
  })
}

const filteredCourses = ref([] as typeof allCuratedCourses.value)
const noMore = ref(false)
const loading = ref(false)

const page = ref(1)
const pageSize = 8

//获取热门推荐数据
function getCuratedCourses() {
  //分页和类型参数
  const queryParams = {
    pageNo: 1,           // 第1页
    pageSize: 6,        // 每页6条
    //trainingId: 123,
    type: 0
  }
  post('/training/all', queryParams).then(res => {
    //console.log("res",res)
    //TODO:很多页面需要展示的数据没有获取
    allpopularRecommendationCourses.value = res.data.map((item: CourseItem) => ({
      teacher_name: item.columns.teacher_name,
      cover: item.columns.cover,
      teachers_pic: item.columns.teachers_pic,
      title: item.columns.title,
      price: item.columns.price,
      member_id: item.columns.member_id,
      member_number: item.columns.member_number,
      create_time: item.columns.create_time,
      type: item.columns.type,
      id: item.columns.id
    }));
  })
}

function loadMore() {
  fetchRecords()
}

function fetchRecords() {
  if (noMore.value || loading.value) return
  loading.value = true
  page.value += 1
  popularRecommendation(activeCategory.value, true)
  setTimeout(() => {
    loading.value = false
  }, 500)
}

getDataLabels()
let newItems = []
//获取数据标签
function getDataLabels() {
  post('/dictionary/trainingLabel').then(res => {
    newItems = res.data.map((item:any) => ({
      ...item.columns
    }))
    categories = [
        ...categories,
        ...newItems
    ]
    console.log("categories", categories)
    if (categories.length > 0) {
      activeCategory.value = categories[0].id; // 关键：初始化为第一个分类的id
    }
  })
}

function loadData() {
  page.value = 1
  noMore.value = false
  popularRecommendation(activeCategory.value, false)
}

// Taro原生下拉刷新（小程序/APP）
usePullDownRefresh(() => {
  loadData()
  setTimeout(() => {
    Taro.stopPullDownRefresh()
  }, 1000)
})

// Taro原生触底加载下一页（小程序/APP）
useReachBottom(() => {
  fetchRecords()
})

// 返回上一页
const goBack = () => {
  Taro.navigateBack({
    delta: 1,
  });
};

// 初始化
onMounted(() => {
  popularRecommendation(0, false)
})

// 分类数据
let categories = [
  {
    commission: null,
    create_time: null,
    id: 0,
    name: "全部",
    pic: null,
    update_time: null,
  }
  /*{name: "编程", icon: "icon-code"},
  {name: "设计", icon: "icon-paint-brush"},
  {name: "营销", icon: "icon-chart-line"},
  {name: "语言", icon: "icon-language"},
  {name: "音乐", icon: "icon-music"},
  {name: "摄影", icon: "icon-camera"},
  {name: "商业", icon: "icon-briefcase"},*/
];


// 活跃状态
const activeCategory = ref();
const activeNav = ref(0);

// 监听activeCategory变化，重新查询数据
watch(activeCategory, (newCategory) => {
  if (newCategory !== undefined) {
    // 重置分页
    page.value = 1
    noMore.value = false
    // 重新查询数据
    popularRecommendation(newCategory, false)
  }
})

// 处理课程点击
const handleCourseClick = (item: any) => {
  console.log("item",item)
  // Taro.showToast({
  //   title: `即将进入课程: ${title}`,
  //   icon: "none",
  //   duration: 2000,
  // });
  //console.log("ID",item.id)
  Taro.navigateTo({
    url: `/pages/course/detail?id=${item.id}`,
  });
};

// 处理学习路径点击
const handlePathClick = (pathName: any) => {
  Taro.showToast({
    title: `开始${pathName}学习路径！`,
    icon: "none",
    duration: 2000,
  });
};
//显示当前热门推荐内容
const currentPopularRecommendationCourses = computed(() => {
  // 确保源数据和category都存在，避免空值错误
  if (!allpopularRecommendationCourses.value || !activeCategory.value) {
    return [];
  }

  // 筛选出type与category.id相等的数据
  return allpopularRecommendationCourses.value.filter(item => {
    // 额外处理item.type和category.id可能为null/undefined的情况
    return item.type === activeCategory.value;
  });
});
//显示当前精品课程内容
const currentCuratedCourses = computed(() => {
  //console.log("activeCategory",activeCategory.value)
  if(activeCategory.value === 0){
    return allCuratedCourses.value
  }
  // 确保源数据和category都存在，避免空值错误
  if (!allCuratedCourses.value || !activeCategory.value) {
    return [];
  }
  // 筛选出type与category.id相等的数据
  return allCuratedCourses.value.filter(item => {
    // 额外处理item.type和category.id可能为null/undefined的情况
    return item.type === activeCategory.value;
  });
});
const goMore = (n: any) => {
  Taro.navigateTo({
    url: '/pages/course/list'
  })
}
</script>

<style scoped lang="scss">
.bigs{
  :deep(img){
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}
</style>
